//
//  ShoppingProductDetailViewController.m
//  PeopleStreet
//
//  Created by 喻飞 on 15/12/29.
//  Copyright © 2015年 yuf. All rights reserved.
//

#import "ShoppingProductDetailViewController.h"
#import "UMSocialScreenShoter.h"
#import "UMSocialShakeService.h"
#import "UMSocialControllerService.h"
#import "UIImageView+WebCache.h"
#import "CommitStarsView.h"
#import <UIImageView+RJLoader.h>
#import "CommentTableViewCell.h"
#import "SureIndentViewController.h"
#import "AttributScroView.h"
#import "AppGoodsPerporty.h"
#import "ShopViewController.h"
#import "ShoppingHomeGuessProductCollection.h"
#import "ForSalePaperTableViewCell.h"
#import "ZBroswerView.h"
static NSString *cellWithIdentifier = @"ForSalePaperTableViewCell";
static NSString *cellIdentify = @"CommentTableViewCell";
static NSString *CellWithGuessIdentifier = @"ShoppingHomeGuessProductCollection";
@interface ShoppingProductDetailViewController ()<DYQBannerScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,MWPhotoBrowserDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong,nonatomic) DYQBannerScrollView *bannerScrollView;//广告栏

@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property(nonatomic,strong)NSMutableArray * goodsGuessLikeArray;//猜你喜欢商品
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIButton *goodsButton;
@property (strong, nonatomic) IBOutlet UIButton *detailButton;
@property(nonatomic,assign)NSInteger selectedIndex;
@property (strong, nonatomic) IBOutlet UIButton *commentButton;
@property (strong, nonatomic) IBOutlet UIScrollView *detailScroView;//详情scroview
@property (strong, nonatomic) IBOutlet UITableView *commentTableView;//评论tableView


///////////////////////////////////商品
@property (strong, nonatomic) IBOutlet UILabel *goodsName;//名字
@property (strong, nonatomic) IBOutlet UILabel *shopName;

@property (strong, nonatomic) IBOutlet UILabel *goodsPrice;//价钱及积分
@property (weak, nonatomic) IBOutlet UILabel *productOriginalPrice;//原价
@property (strong, nonatomic) IBOutlet UIButton *disCount;//折扣
@property (strong, nonatomic) IBOutlet UILabel *forSaleLabel;//促销
@property (strong, nonatomic)
IBOutlet UILabel *saleLabel;//优惠劵
@property (strong, nonatomic) IBOutlet UILabel *choseType;//选择尺码
@property (strong, nonatomic) IBOutlet UILabel *postPrice;//运费
@property (strong, nonatomic) IBOutlet UILabel *ServiceLabel;//服务
@property (strong, nonatomic) IBOutlet UILabel *addressLabel;//地址
@property (strong, nonatomic) IBOutlet UILabel *telephoneLabel;//电话
@property (strong, nonatomic) IBOutlet UIView *ServiceStars;//服务星
@property (strong, nonatomic) IBOutlet UIView *goodsStars;//商品星
@property (weak, nonatomic) IBOutlet UIView *IntegralBuy;//积分购 行 视图
@property (weak, nonatomic) IBOutlet UILabel *IntegralBuyLabel;//积分购label

@property (weak, nonatomic) IBOutlet UIView *bottomView;//优惠券以下视图

///////////////////////////////////详情

////////////////////////////////////评论
@property (strong, nonatomic) IBOutlet UIView *commentLine;
@property (strong, nonatomic) IBOutlet UILabel *commentLabel;//评论条数


@property (strong, nonatomic) IBOutlet UIView *changePropertyView;//修改款式View
@property (strong, nonatomic) IBOutlet UIButton *sureChangeButton;//确认修改按钮
@property (strong, nonatomic) IBOutlet UIButton *putInShopCarButton;

@property (strong, nonatomic) IBOutlet UIView *propertyView;//款式View
@property (strong, nonatomic) IBOutlet UIButton *addButton;
@property (strong, nonatomic) IBOutlet UILabel *productNumber;
@property (strong, nonatomic) IBOutlet UIButton *deleteButton;
@property (strong, nonatomic) IBOutlet UIImageView *propertyImage;//修改尺码图片

@property (strong, nonatomic) IBOutlet UILabel *propertyPrice;//修改尺码价格
@property (strong, nonatomic) IBOutlet UILabel *propertyNumber;//修改尺码库存

@property (strong, nonatomic) IBOutlet UILabel *typeAndSize;//修改尺码尺码
@property (weak, nonatomic) IBOutlet UICollectionView *goodsCollectionView;//猜你喜欢商品数据

@property(nonatomic,strong)NSString * mgspId;
@property(nonatomic,strong)NSString * mgspPrice;

@property(nonatomic,strong)NSMutableArray * commitArray;
@property(nonatomic,strong)NSMutableArray * heightArray;
@property(nonatomic,strong)NSArray * goodsInfoArray;
@property(nonatomic,strong)NSMutableArray * photos;
@property(nonatomic,strong)MWPhotoBrowser * browser;
//规格
@property (strong, nonatomic) NSMutableDictionary *perportyDic;
@property (strong, nonatomic) NSMutableArray *perportyOneArr;
@property (strong, nonatomic) NSMutableArray *perportyTwoArr;
@property (strong, nonatomic) IBOutlet UIButton *collectButton;


@property (strong, nonatomic) IBOutlet UILabel *goodsServiceName;
@property (strong, nonatomic) IBOutlet UIButton *maskForSaleButton;
@property (strong, nonatomic) IBOutlet UITableView *forSaleTableView;
@property (strong, nonatomic) IBOutlet UIView *forSalePaperView;
@property(strong,nonatomic)NSMutableArray * couponArray;
@property (strong, nonatomic) NSString *productDetailWebUrl;//商品详情地址
@end

@implementation ShoppingProductDetailViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if([Common getLoginStatus]){
        [self getBagNumber];
        [self ifGoodsCollect];
        [self queryProductDetailWeb];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //会员浏览商品
    
    _selectedIndex = 100;
    _pageNO =  1;
    _perportyDic = [NSMutableDictionary dictionary];
    _perportyOneArr = [NSMutableArray array];
    _perportyTwoArr = [NSMutableArray array];
    _commitArray = [NSMutableArray array];
    _photos = [NSMutableArray array];
    _goodsGuessLikeArray = [NSMutableArray array];
    _couponArray = [NSMutableArray array];
    self.productDetailWebUrl = @"";
    [self initViewLayout];
    [self getGoodsInfo];
    [self getIntegralBuyInfo];
    //猜你喜欢
    [self getGuessGoods];
    [self getGoodsService];
    [self userScanProduct:self.goodsId];
}
#pragma mark  布局调整--=========================================
- (void)initViewLayout{

 
    //产品标题栏--原始价格
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:self.productOriginalPrice.text];
    [str addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, str.length)];
    self.productOriginalPrice.attributedText = str;

    //功能栏
    [self adaptiveViewLayout:self.view];
     [self adaptiveViewLayout:_navView];
    [self adaptiveViewLayout:self.mainScroll];
     [self adaptiveViewLayout:self.bottomView];
    [self adaptiveViewLayout:self.detailScroView];
    [self adaptiveViewLayout:self.commentTableView];
    [self adaptiveViewLayout:self.productTitleView];
    [self adaptiveViewLayout:self.forSaleView];
    [self adaptiveViewLayout:self.choseTypeView];
    [self adaptiveViewLayout:self.ServiceView];
    [self adaptiveViewLayout:self.IntegralBuy];
    [self adaptiveViewLayout:self.productDiscountCouponView];
    [self adaptiveViewLayout:self.productFreightPriceView];
    [self adaptiveViewLayout:self.commpanyTitleView];
    [self adaptiveViewLayout:self.productDetailImageView];
    [self adaptiveViewLayout:self.productDetailBottomView];
    [self adaptiveViewLayout:self.forSalePaperView];
    
    [self adaptiveViewLayout:self.changePropertyView];
    [self adaptiveViewLayout:self.propertyView];
    [self adaptiveViewLayout:self.goodsCollectionView];
    
    
    
    self.bannerScrollView = [[DYQBannerScrollView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 320), NO)];
    self.bannerScrollView.backgroundColor = [UIColor clearColor];
    self.bannerScrollView.pageControlPosition = PageControlPositionCenter;
    self.bannerScrollView.noDataPlaceholderImage = [UIImage imageNamed:@"cover_cy"];
    self.bannerScrollView.timeInterval = 3;
    self.bannerScrollView.pageControllerTintColor = [UIColor whiteColor];
    self.bannerScrollView.pageControllerCurrentColor = [UIColor orangeColor];
    
    [self.mainScroll addSubview:_bannerScrollView];

    self.changePropertyView.hidden = YES;
    
    self.mainScroll.contentSize = flexibleSize(CGSizeMake(0, 995), NO);
    self.detailScroView.contentSize = flexibleSize(CGSizeMake(0, 960), NO);
    
    _addButton.layer.masksToBounds = YES;
    _addButton.layer.borderColor = [UIColor colorWithWhite:0.898 alpha:1.000].CGColor;
    _addButton.layer.borderWidth = 1;
    
    _deleteButton.layer.masksToBounds = YES;
    _deleteButton.layer.borderColor = [UIColor colorWithWhite:0.898 alpha:1.000].CGColor;
    _deleteButton.layer.borderWidth = 1;
    
    _productNumber.layer.masksToBounds = YES;
    _productNumber.layer.borderColor = [UIColor colorWithWhite:0.898 alpha:1.000].CGColor;
    _productNumber.layer.borderWidth = 1;

    
    
    [_goodsButton setTitleColor:[UIColor colorWithRed:1.000 green:0.710 blue:0.082 alpha:1.000] forState:UIControlStateSelected];
    [_goodsButton setTitleColor:[UIColor colorWithWhite:0.275 alpha:1.000] forState:UIControlStateNormal];
    _goodsButton.selected = YES;
    
    [_detailButton setTitleColor:[UIColor colorWithRed:1.000 green:0.710 blue:0.082 alpha:1.000] forState:UIControlStateSelected];
    [_detailButton setTitleColor:[UIColor colorWithWhite:0.275 alpha:1.000] forState:UIControlStateNormal];
    [_commentButton setTitleColor:[UIColor colorWithRed:1.000 green:0.710 blue:0.082 alpha:1.000] forState:UIControlStateSelected];
    [_commentButton setTitleColor:[UIColor colorWithWhite:0.275 alpha:1.000] forState:UIControlStateNormal];
    
    
    
    self.productNumLabel.layer.masksToBounds = YES;
    self.productNumLabel.layer.cornerRadius = 6*VerticalRatio();
    self.imageArray = [NSMutableArray array];
    
    CommitStarsView * sstars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)), NO) Stars:3.5];
    [_ServiceStars addSubview:sstars];
    CommitStarsView * gstars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)), NO) Stars:3.5];
    [_goodsStars addSubview:gstars];
    
    //注册
    [self.commentTableView registerClass:[CommentTableViewCell class]  forCellReuseIdentifier:cellIdentify];
    self.commentTableView.separatorStyle = NO;
    
    
    [self.forSaleTableView registerNib:[UINib nibWithNibName:cellWithIdentifier bundle:nil] forCellReuseIdentifier:cellWithIdentifier];

    
    
    _browser = [[MWPhotoBrowser alloc] init];
    
    // Set options
    _browser.displayActionButton = YES; // Show action button to allow sharing, copying, etc (defaults to YES)
    _browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    _browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    _browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    _browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    _browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    _browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
    
    // Optionally set the current visible photo before displaying
    // Manipulate
    [_browser showNextPhotoAnimated:YES];
    [_browser showPreviousPhotoAnimated:YES];

    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.goodsCollectionView.collectionViewLayout = flowLayout;
    self.goodsCollectionView.backgroundColor =kGetColor(255, 255, 255);
    self.goodsCollectionView.userInteractionEnabled=YES;
    [self.goodsCollectionView registerNib:[UINib nibWithNibName:CellWithGuessIdentifier bundle:nil] forCellWithReuseIdentifier:CellWithGuessIdentifier];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.commentTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.commentTableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getCommentsInfo];
        });
    }];
    // 马上进入刷新状态
    [self.commentTableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.commitArray.count == _totle) {
        [self.commentTableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getCommentsInfo];
        });
    }
    
}

#pragma mark  获取购物袋数量--=========================================
-(void)getBagNumber{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryCartProductTotalNum" forKey:@"method"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"userId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryCartProductTotalNum withHttpType:@"POST" withTag:SX_QueryCartProductTotalNum];
}

#pragma mark  获取店铺优惠券--=========================================
-(void)getStoreForSale{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_goodsInfoArray[0][@"mallStoreId"] forKey:@"storeId"];
    if (![Common getLoginStatus]) {
        [dic setObject:@"" forKey:@"userId"];
    }else{
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"userId"];
    }
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryDesc withHttpType:@"POST" withTag:SX_SX_queryDesc];
}

#pragma mark  获取积分购=========================================
-(void)getIntegralBuyInfo{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_querySpendingSys withHttpType:@"POST" withTag:SX_SX_querySpendingSys];
}

#pragma mark == 获取商品信息
- (void)getGoodsInfo{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryMallGoodsDetailData" forKey:@"method"];
    [dic setObject:_goodsId forKey:@"mgooId"];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_GoodsInfo withHttpType:@"POST" withTag:SX_fruitDetailTag];

}
#pragma mark == 获取评论
- (void)getCommentsInfo{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_goodsId forKey:@"mgooId"];

    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGoodsCommentData withHttpType:@"POST" withTag:SX_SX_queryGoodsCommentData];
    
    
}
#pragma mark == 查询猜你喜欢商品
- (void)getGuessGoods{
    if ([Common getLoginStatus]) {
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_QueryMallUserLoveGoodsData withHttpType:@"POST" withTag:SX_QueryMallLoveGoodsDataTag];
    }else{
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:@"queryMallLoveGoodsData" forKey:@"method"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_QueryMallLoveGoodsData withHttpType:@"POST" withTag:SX_QueryMallLoveGoodsDataTag];
    }
    
}
- (IBAction)changeSelectedIndex:(UIButton *)sender {
    if (sender.tag==_selectedIndex) {
        return;
    }
    sender.selected = YES;
    UIButton * button = (UIButton *)[self.view viewWithTag:_selectedIndex];
    button.selected = NO;
    _selectedIndex = sender.tag;
    
    [UIView animateWithDuration:0.5 animations:^{
        
            _mainScroll.frame = flexibleFrame(CGRectMake(-320*(_selectedIndex-100), 64, 320, 457), NO);
            _detailScroView.frame = flexibleFrame(CGRectMake(320-320*(_selectedIndex-100), 64,320, 457), NO);
            _commentTableView.frame =flexibleFrame(CGRectMake(640-320*(_selectedIndex-100), 116, 320, 407), NO);
            _commentLabel.frame = flexibleFrame(CGRectMake(655-320*(_selectedIndex-100) , 81, 150, 21), NO);
            _commentLine.frame = flexibleFrame(CGRectMake(640-320*(_selectedIndex-100) , 111, 320, 5), NO);

           }];
    
    if (_selectedIndex == 101) {
        
        
    }else if (_selectedIndex == 102){
        [self addRefreshing];
    }
}


- (IBAction)back:(id)sender {
        _mainScroll.hidden = YES;
        _detailScroView.hidden = YES;
    
    [self.navigationController  popViewControllerAnimated:YES];
    
}

#pragma mark == 打开优惠劵
- (IBAction)saleHandel:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{
        _forSalePaperView.frame = flexibleFrame(CGRectMake(0, 225, 320, 343), YES);
        _maskForSaleButton.hidden = NO;
    }];
}
#pragma mark == 关闭优惠劵页面
- (IBAction)closeForsaleView:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{
        _forSalePaperView.frame = flexibleFrame(CGRectMake(0, 568, 320, 343), YES);
        _maskForSaleButton.hidden = YES;
    }];
}
#pragma mark == 选择尺码
- (IBAction)choseType:(id)sender {
    [self getTypes];
}

- (void)getTypes{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryGoodsUpProperty" forKey:@"method"];
    [dic setObject:_goodsId forKey:@"mgooId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGoodsUpProperty withHttpType:@"POST" withTag:SX_QueryGoodsUpProperty];
    
    
    self.changePropertyView.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        self.sureChangeButton.frame = flexibleFrame(CGRectMake(160, 524, 160, 44), NO);
        self.putInShopCarButton.frame = flexibleFrame(CGRectMake(0, 524, 160, 44), NO);
        self.propertyView.frame = flexibleFrame(CGRectMake(0, 180, 320, 344), NO);
        self.changePropertyView.alpha = 1;
        
        NSString *appAdertImagUriName = _goodsInfoArray[0][@"appAdertImagUriName"];
        NSArray *urlArr = [appAdertImagUriName componentsSeparatedByString:@","];
        NSString *image = urlArr[0];
        if (image.length>0) {
            [_propertyImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }else{
            _propertyImage.image =[UIImage imageNamed:@"cloth1"];
        }
    }];
    //
    //        _propertyPrice.text = [NSString stringWithFormat:@"￥%@",_goodsArray[indexPath.section][@"appAdertImagUri"][indexPath.row][@"mgooPublishPrice"]];
}
     
#pragma mark ---------- 隐藏修改款式View
- (IBAction)hideChangeView:(id)sender {
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.sureChangeButton.frame = flexibleFrame(CGRectMake(160, 524+567, 160, 44), NO);
       self.putInShopCarButton.frame = flexibleFrame(CGRectMake(0, 524+567, 160, 44), NO);
        self.propertyView.frame = flexibleFrame(CGRectMake(0, 180+567, 320, 344), NO);
        self.changePropertyView.alpha = 0;
    } completion:^(BOOL finished) {
        self.changePropertyView.hidden = YES;
    }];
    
    for (UIView * view in _propertyView.subviews) {
        if ([view isKindOfClass:[AttributScroView class]]) {
            [view removeFromSuperview];
        }
    }
    
}

#pragma mark == 减少商品数量
- (IBAction)deleteProductNumber:(id)sender {
    NSInteger number = [_productNumber.text integerValue];
    if (number==1) {
        
    }else{
    number -= 1;
    }
    _productNumber.text = [NSString stringWithFormat:@"%ld",number];
}
#pragma mark == 增加商品数量
- (IBAction)addProductNumber:(id)sender {
    NSInteger number = [_productNumber.text integerValue];
    number += 1;
    _productNumber.text = [NSString stringWithFormat:@"%ld",number];
}

#pragma mark ---------- 确认修改款式View加入购物车
- (IBAction)putInShopCar:(id)sender {
    
    [UIView animateWithDuration:0.5 animations:^{
        self.sureChangeButton.frame = flexibleFrame(CGRectMake(160, 524+567, 160, 44), NO);
        self.putInShopCarButton.frame = flexibleFrame(CGRectMake(0, 524+567, 160, 44), NO);
        self.propertyView.frame = flexibleFrame(CGRectMake(0, 180+567, 320, 344), NO);
        self.changePropertyView.alpha = 0;
    } completion:^(BOOL finished) {
        self.changePropertyView.hidden = YES;
        
    }];
    
    for (UIView * view in _propertyView.subviews) {
        if ([view isKindOfClass:[AttributScroView class]]) {
            [view removeFromSuperview];
        }
    }
    
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
    }else{
        
        if ([Common dataIsNULL:_mgspId]) {
            [[CWHUDTips sharedInstance]  showTips:@"请选择商品规格"];
            [self getTypes];
            return;
        }
        
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:@"addCartInfo" forKey:@"method"];
        [dic setObject:_goodsId forKey:@"mcdeGoodsId"];
        [dic setObject:_productNumber.text forKey:@"productNum"];
        [dic setObject:_mgspId forKey:@"mcdeUpspecifyId"];
        [dic setObject:_mgspPrice forKey:@"mcdeInPrice"];
        
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_PutInShoppingCar withHttpType:@"POST" withTag:SX_SX_PutInShopCar];
    }
}


#pragma mark ---------- 确认修改款式View立即购买
- (IBAction)sureChange:(id)sender {
    
    [UIView animateWithDuration:0.5 animations:^{
        self.sureChangeButton.frame = flexibleFrame(CGRectMake(160, 524+567, 160, 44), NO);
        self.putInShopCarButton.frame = flexibleFrame(CGRectMake(0, 524+567, 160, 44), NO);
        self.propertyView.frame = flexibleFrame(CGRectMake(0, 180+567, 320, 344), NO);
        self.changePropertyView.alpha = 0;
    } completion:^(BOOL finished) {
        self.changePropertyView.hidden = YES;
        
    }];
    
    for (UIView * view in _propertyView.subviews) {
        if ([view isKindOfClass:[AttributScroView class]]) {
            [view removeFromSuperview];
        }
    }

    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
    }else{
        if ([Common dataIsNULL:_mgspId]) {
            [[CWHUDTips sharedInstance]  showTips:@"请选择商品规格"];
            [self getTypes];
            return;
        }
        
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        SureIndentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SureIndent"];
        NSMutableArray *goodsArray = [NSMutableArray array];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:_goodsInfoArray[0][@"mgooName"] forKey:@"mgooName"];
        [dic setObject:_goodsInfoArray[0][@"mallStoreName"] forKey:@"mallStoreName"];
        //  NSString *urlName = _imageArray[0];
        [dic setObject:_goodsInfoArray[0][@"appAdertImagUriName"] forKey:@"appAdertImagUriName"];
        [dic setObject:_goodsInfoArray[0][@"mgooId"] forKey:@"mgooId"];
        [dic setObject:_goodsInfoArray[0][@"mallStoreId"] forKey:@"mallStoreId"];
        [dic setObject:_mgspId forKey:@"mcdeUpspecifyId"];
        [dic setObject:_goodsInfoArray[0][@"mgseSpecifyDetailJson"] forKey:@"mgseSpecifyDetailJson"];
        [dic setObject:_productNumber.text forKey:@"goodsCartNum"];
        [dic setObject:_goodsInfoArray[0][@"mgooPublishPrice"] forKey:@"mgooPublishPrice"];
        [goodsArray addObject:dic];
        page.goodsInfoArray = goodsArray;
        page.number = _productNumber.text;
        page.countMoney = [NSString stringWithFormat:@"%f",[_goodsInfoArray[0][@"mgooPublishPrice"]floatValue] * [_productNumber.text integerValue]] ;
        page.payType = @"1";
        [self.navigationController   pushViewController:page animated:YES];
    }

    
}

#pragma mark === 查询商品是否收藏
- (void)ifGoodsCollect{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_goodsId forKey:@"goodsId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGoodsIsCollect withHttpType:@"POST" withTag:SX_SX_queryGoodsIsCollect];
    
   
}
#pragma mark === 查询商品详情web内容
- (void)queryProductDetailWeb{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_goodsId forKey:@"goodsId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGoodsDetailsWeb withHttpType:@"POST" withTag:SX_queryGoodsDetailsWebTag];
}
#pragma mark === 查询商品服务
- (void)getGoodsService{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_goodsId forKey:@"goodsId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_querySerivceNameByGoodsId withHttpType:@"POST" withTag:SX_SX_querySerivceNameByGoodsId];
}

#pragma mark == 进入店铺
- (IBAction)goToShop:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ShopViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Shop"];
    page.storeId = _goodsInfoArray[0][@"mallStoreId"];
    [self.navigationController   pushViewController:page animated:YES];
}
#pragma mark == 运费
- (IBAction)postPrice:(id)sender {
}
#pragma mark == 电话
- (IBAction)call:(id)sender {
    [Common callPhone:_goodsInfoArray[0][@"mstoPhone"] view:self.view];
}
#pragma mark == 收藏
- (IBAction)collect:(id)sender {
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
    }else{
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:@"addGoodsCollectInfo" forKey:@"method"];
        [dic setObject:@"1" forKey:@"collectType"];
        [dic setObject:_goodsId forKey:@"goodsId"];
        [dic setObject:@"" forKey:@"storeType"];

        [dic setObject:_goodsInfoArray[0][@"mgooPublishPrice"] forKey:@"goodsPrice"];
        
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_AddGoodsCollectInfo withHttpType:@"POST" withTag:SX_AddGoodsCollectInfoTag];
    }
}
#pragma mark == 分享
- (IBAction)share:(id)sender {
    //分享内嵌文字
    NSString *shareText;
    shareText = [NSString stringWithFormat:@"凡人街在线商城"];
    
    UIImage *shareImage = [UIImage imageNamed:@"58"];          //分享内嵌图片
    
    //调用快速分享接口
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:UmengAppkey
                                      shareText:shareText
                                     shareImage:shareImage
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite,UMShareToQQ,UMShareToQzone,nil]
                                       delegate:nil];
}
#pragma mark == 加入购物车
- (IBAction)putInShoppingBag:(id)sender {
    
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
    }else{
    
        if ([Common dataIsNULL:_mgspId]) {
            [[CWHUDTips sharedInstance]  showTips:@"请选择商品规格"];
            [self getTypes];
            return;
        }
        
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"addCartInfo" forKey:@"method"];
    [dic setObject:_goodsId forKey:@"mcdeGoodsId"];
    [dic setObject:_productNumber.text forKey:@"productNum"];
    [dic setObject:_mgspId forKey:@"mcdeUpspecifyId"];
    [dic setObject:_mgspPrice forKey:@"mcdeInPrice"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_PutInShoppingCar withHttpType:@"POST" withTag:SX_SX_PutInShopCar];
    }
}
#pragma mark == 马上购买
- (IBAction)buyNow:(id)sender {
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
    }else{
        if ([Common dataIsNULL:_mgspId]) {
            [[CWHUDTips sharedInstance]  showTips:@"请选择商品规格"];
            [self getTypes];
            return;
    }
        
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    SureIndentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SureIndent"];
    NSMutableArray *goodsArray = [NSMutableArray array];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:_goodsInfoArray[0][@"mgooName"] forKey:@"mgooName"];
    [dic setObject:_goodsInfoArray[0][@"mallStoreName"] forKey:@"mallStoreName"];
//  NSString *urlName = _imageArray[0];
    [dic setObject:_goodsInfoArray[0][@"appAdertImagUriName"] forKey:@"appAdertImagUriName"];
    [dic setObject:_goodsInfoArray[0][@"mgooId"] forKey:@"mgooId"];
    [dic setObject:_goodsInfoArray[0][@"mallStoreId"] forKey:@"mallStoreId"];
    [dic setObject:_mgspId forKey:@"mcdeUpspecifyId"];
    [dic setObject:_goodsInfoArray[0][@"mgseSpecifyDetailJson"] forKey:@"mgseSpecifyDetailJson"];
        [dic setObject:_productNumber.text forKey:@"goodsCartNum"];
       [dic setObject:_goodsInfoArray[0][@"mgooPublishPrice"] forKey:@"mgooPublishPrice"];  
    [goodsArray addObject:dic];
    page.goodsInfoArray = goodsArray;
    page.number = @"1";
    page.countMoney = [NSString stringWithFormat:@"%f",[_goodsInfoArray[0][@"mgooPublishPrice"]floatValue] * [_productNumber.text integerValue]];
    page.payType = @"1";
    [self.navigationController   pushViewController:page animated:YES];
    }
}
#pragma mark == 购物车
- (IBAction)shoppingBag:(id)sender {
    
    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
    }else{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ShoppingBag"];
    [self.navigationController   pushViewController:page animated:YES];
    }
}

#pragma mark == 展示评论图片
- (void)showImage:(UIButton *)sender{
    [_photos removeAllObjects];
    NSArray * imageArray =  _commitArray[sender.tag/100-1][@"imageArray"];
    for (NSString * str in imageArray) {
        MWPhoto * photo = [MWPhoto photoWithURL:[NSURL URLWithString:str]];
        [_photos addObject:photo];
    }
    _browser.delegate = self;
    [_browser setCurrentPhotoIndex:sender.tag%100];
    // Present
//    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:_browser];
//    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//    [self presentViewController:nc animated:YES completion:nil];
    [self.navigationController pushViewController:_browser animated:YES];
}

#pragma mark----DYQBannerScrollViewDelegate

-(void)bannerScrollView:(DYQBannerScrollView *)bannerScrollView didSelectItemAtIndex:(NSInteger)index
{
    [_photos removeAllObjects];
    [_imageArray removeAllObjects];
    NSString *appAdertImagUriName = _goodsInfoArray[0][@"appAdertImagUriName"];
    NSArray *urlArr = [appAdertImagUriName componentsSeparatedByString:@","];
    for (NSString *url in urlArr) {
        [self.imageArray addObject:[Common stringFromData:url]];
        MWPhoto * photo = [[MWPhoto alloc]initWithURL:[NSURL URLWithString:url]];
        [_photos addObject:photo];
    }
    
//    _browser.titleStr = [NSString stringWithFormat:@"%@",_goodsInfoArray[0][@"mgooName"]];
//    _browser.delegate = self;
//    [_browser setCurrentPhotoIndex:index];
//    // Present
//    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:_browser];
//    [self presentViewController:nc animated:YES completion:nil];
    
    
    ZBroswerView * broswer = [[ZBroswerView alloc] initWithImageArray:[_imageArray copy] currentIndex:index];
    broswer.titleStr = _goodsName.text;
    [broswer showInCell:self.view];

}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < self.photos.count) {
        return [self.photos objectAtIndex:index];
    }
    return nil;
}

- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index{
    NSString * str = [NSString stringWithFormat:@"%ld/%ld",index+1,_photos.count];
    return str;
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _forSaleTableView) {
        ForSalePaperTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellWithIdentifier];
        if (cell == nil) {
            cell= [[ForSalePaperTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellWithIdentifier];
        }
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        NSDictionary * dic= _couponArray[indexPath.row];
        cell.forSaleMoney.text = [NSString stringWithFormat:@"%@元",dic[@"mscoDecreaseAmount"]];
        cell.forSaleInfo.text =[NSString stringWithFormat:@"订单满%@.00元使用", dic[@"mscoFullAmount"]];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[dic[@"mscoefficacyDate"] integerValue]/1000];
        NSDate *confromTimesp1 = [NSDate dateWithTimeIntervalSince1970:[dic[@"mscoInvalidateDate"] integerValue]/1000];
        [formatter setDateFormat:@"yyyy.MM.dd"];
        NSString *beginTime = [formatter stringFromDate:confromTimesp];
        NSString *endTime = [formatter stringFromDate:confromTimesp1];
        cell.forSaleDate.text = [NSString stringWithFormat:@"使用期限 %@ - %@",beginTime,endTime];
        
        cell.getPaperBlock = ^(NSString * str){
            if ([str isEqualToString:@"1"]) {
                NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
                [dic setObject:_couponArray[indexPath.row][@"mscoId"] forKey:@"counponId"];
                self.shareApi.delegate=self;
                [self.shareApi  requestOperationWithDic:dic withPath:SX_saveUserConpon withHttpType:@"POST" withTag:SX_SX_saveUserConpon];
            }
        };
        return cell;
    }else{
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify forIndexPath:indexPath];
    if (!cell) {
        cell = [[CommentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    CommitStarsView * stars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(15, 47, 80, 15), NO) Stars:[_commitArray[indexPath.row][@"productCommentStars"]floatValue]];
    [cell addSubview:stars];
    cell.timeLabel.text =_commitArray[indexPath.row][@"productCommentDate"] ;
    NSString * imageUrl =  _commitArray[indexPath.row][@"productCommentUserIcon"];
    if (imageUrl.length>0) {
        [cell.headImage sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
    }else
    {
    cell.headImage.image = [UIImage imageNamed:@"comment1"];
    }
    cell.personName.text =  [NSString stringWithFormat:@"%@",_commitArray[indexPath.row][@"productCommentUserName"]];
    cell.commentWords.text = _commitArray[indexPath.row][@"commentArray"][0];
    [cell.commentWords sizeToFit];
    
    cell.imageArray = _commitArray[indexPath.row][@"imageArray"];
    cell.commentArray = _commitArray[indexPath.row][@"commentArray"];
    
    
    cell.propertyLabel.frame = flexibleFrame(CGRectMake(15, [_heightArray[indexPath.row] integerValue]-25, 280, 0), NO);
    cell.propertyLabel.text = _commitArray[indexPath.row][@"productPorpertyJson"];
    [cell.propertyLabel sizeToFit];
    
    
    NSString * comment =cell.commentArray[0];
    CGSize comSize = [comment sizeWithFont:[UIFont systemFontOfSize:14*VerticalTexeRatio()]];
    NSInteger Y;
    if (comSize.width<290*VerticalRatio()) {
        Y=comSize.height;
    }else{
        Y=(comSize.width/290+1)*(comSize.height+10);
    }
    //评论
    if (cell.commentArray.count>1) {
        for (int i = 1; i<cell.commentArray.count; i++) {
            //            NSString * string1 = cell.commentArray[i][@"nickname"];
            //            NSString * string2 = cell.commentArray[i][@"replycontent"];
            //            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@",string1,string2]];
            //            [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.153 green:0.204 blue:0.329 alpha:1.000] range:NSMakeRange(0,string1.length)];
            
            UILabel * label = [[UILabel alloc]init];
            if (cell.imageArray.count>0) {
                label.frame = flexibleFrame(CGRectMake(15, 135+Y+(i-1)*17, 290, 15), NO);
            }else{
                label.frame = flexibleFrame(CGRectMake(15, 80+Y+(i-1)*20, 290, 15), NO);
            }
            label.textColor = [UIColor colorWithWhite:0.200 alpha:1.000];
            label.backgroundColor = [UIColor whiteColor];
            label.textAlignment = NSTextAlignmentLeft;
            label.font = [UIFont systemFontOfSize:11*VerticalRatio()];
            //            label.attributedText = str;
            label.text = cell.commentArray[i];
            [cell addSubview:label];
        }
        
        
    }
    
    if (cell.imageArray.count>0) {
        
        UIScrollView * scroView = [[UIScrollView alloc]initWithFrame:flexibleFrame(CGRectMake(17, 70+Y, 283, 50), NO)];
        scroView.contentSize = flexibleSize(CGSizeMake(50*cell.imageArray.count+1, 50), NO);
        scroView.showsHorizontalScrollIndicator = NO;
        [cell addSubview:scroView];
        
        
        for (int i = 0; i<cell.imageArray.count; i++) {
            UIButton * imageView = [UIButton buttonWithType:UIButtonTypeCustom];
            imageView.frame = flexibleFrame(CGRectMake(55*i, 0, 50, 50), NO);
            imageView.tag = 100*(indexPath.row+1)+i;
            [imageView addTarget:self action:@selector(showImage:) forControlEvents:UIControlEventTouchUpInside];
            NSString * imageUrl = [NSString stringWithFormat:@"%@",cell.imageArray[i]];
            if (imageUrl.length>0) {
               [imageView sd_setBackgroundImageWithURL:[NSURL URLWithString:imageUrl] forState:UIControlStateNormal];
            }else{
                [imageView setBackgroundImage:[UIImage imageNamed:@"comment11"] forState:UIControlStateNormal];
            }
            
            [scroView addSubview:imageView];
        }
    }
    
    UILabel * line = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, [_heightArray[indexPath.row] floatValue]-5, 320, 5), NO)];
    line.backgroundColor =[UIColor colorWithWhite:0.898 alpha:1.000];
    [cell addSubview:line];
    
    return cell;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _forSaleTableView) {
        return _couponArray.count;
    }else{
    return _commitArray.count;
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _forSaleTableView) {
        return 77*VerticalRatio();
    }else{
    NSInteger height= [_heightArray[indexPath.row] integerValue];
    return height*VerticalRatio();
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
   return _goodsGuessLikeArray.count;
    
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(91*VerticalRatio(), 144*VerticalRatio());
    
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
   return UIEdgeInsetsMake(0,10, 0, 10);
    
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingHomeGuessProductCollection * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellWithGuessIdentifier forIndexPath:indexPath];
    NSDictionary *dic = _goodsGuessLikeArray[indexPath.row];
    cell.cellProductName.text = dic[@"mgooName"];
    cell.cellProuctPrice.text = [NSString stringWithFormat:@"￥%.2f",[dic[@"mgooPublishPrice"] floatValue]];
    NSString * image = dic[@"appAdertImagUri"];
    if (image.length>0) {
        [cell.cellProductImage sd_setImageWithURL:[NSURL URLWithString:image]];
    }else{
        cell.cellProductImage.image =[UIImage imageNamed:@"cloth1"];
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    self.goodsId = _goodsGuessLikeArray[indexPath.row][@"mgooId"];
    [self.mainScroll setContentOffset:CGPointMake(0, 0)];
    [self getBagNumber];
    [self ifGoodsCollect];
    [self queryProductDetailWeb];
    [self getGoodsInfo];
    [self getIntegralBuyInfo];
    //猜你喜欢
    [self getGuessGoods];
    [self getGoodsService];
    [self userScanProduct:self.goodsId];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_commentTableView.header endRefreshing];
    if (tag==SX_fruitDetailTag) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {

            _goodsInfoArray = database[@"result"];
            [self getStoreForSale];
            if(_goodsInfoArray.count<1){
                return;
            }
            NSDictionary * dic = _goodsInfoArray[0];
            
            
            NSString * string1 = [Common stringFromData:dic[@"mgooPublishPrice"]];
            NSString * string2 = [Common stringFromData:dic[@"mipuProduceAmount"]];
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@ 购买送%@积分",string1,string2]];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.792 green:0.000 blue:0.090 alpha:1.000] range:NSMakeRange(0,string1.length+1)];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.961 green:0.635 blue:0.161 alpha:1.000] range:NSMakeRange(string1.length+5,string2.length)];
            [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17*VerticalTexeRatio()] range:NSMakeRange(0,string1.length+1)];
            _goodsName.text = dic[@"mgooName"];
            _goodsPrice.attributedText = str;
            _addressLabel.text = dic[@"mstoAddress"];
            _telephoneLabel.text = dic[@"mstoPhone"];
            _shopName.text = [NSString stringWithFormat:@"%@",dic[@"mallStoreName"]];
            
            //判断是否有促销
            NSString * forSale = [NSString stringWithFormat:@"%@",dic[@"msopContent"]];
            if ( [forSale isEqualToString:@""]||[forSale isEqualToString:@"(null)"]) {
                _forSaleView.frame = flexibleFrame(CGRectMake(0, CGRectGetMaxY(_productTitleView.frame)/VerticalRatio(), 320, 0), NO);
                _productDiscountCouponView.frame = flexibleFrame(CGRectMake(0, CGRectGetMaxY(_forSaleView.frame)/VerticalRatio(), 320, 45), NO);
                _bottomView.frame = flexibleFrame(CGRectMake(0, CGRectGetMaxY(_productDiscountCouponView.frame)/VerticalRatio(), 320, 485), NO);
                _mainScroll.contentSize = CGSizeMake(0, CGRectGetMaxY(_bottomView.frame)+1);
            }else{
            _forSaleLabel.text = forSale;
            }
            //判断是否有原价
            NSString * oriPri = [NSString stringWithFormat:@"%@", dic[@"price"]];
            if ([oriPri isEqualToString:@""]||[oriPri isEqualToString:@"(null)"]) {
                _productTitleView.frame = flexibleFrame(CGRectMake(0, 320, 320, 65), NO);
                _forSaleView.frame = flexibleFrame(CGRectMake(0, CGRectGetMaxY(_productTitleView.frame)/VerticalRatio(), 320, 45), NO);
                _productDiscountCouponView.frame = flexibleFrame(CGRectMake(0, CGRectGetMaxY(_forSaleView.frame)/VerticalRatio(), 320, 45), NO);
                _bottomView.frame = flexibleFrame(CGRectMake(0, CGRectGetMaxY(_productDiscountCouponView.frame)/VerticalRatio(), 320, 485), NO);
                _mainScroll.contentSize = CGSizeMake(0, CGRectGetMaxY(_bottomView.frame)+1);
                
            }else{
                _productOriginalPrice.text = [NSString stringWithFormat:@"¥%@", dic[@"price"]];
                
                CGFloat price = [string1 floatValue];
                CGFloat oldPrice = [string2 floatValue];
                CGFloat disCount  = price/oldPrice;
                [_disCount setTitle:[NSString stringWithFormat:@"%.1f",disCount] forState:UIControlStateNormal];
            }
            
            
            
            NSString *appAdertImagUriName = _goodsInfoArray[0][@"appAdertImagUriName"];
            NSArray *urlArr = [appAdertImagUriName componentsSeparatedByString:@","];
            _bannerScrollView.imageUrls = urlArr;
            _bannerScrollView.delegate = self;
            
            NSArray * property = dic[@"goodsPropertyList"];
             CGFloat Y = 0;
            for (int i= 0;i<property.count; i++) {
                UILabel * label = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(13,Y, 80, 25), YES)];
                label.textColor = [UIColor colorWithWhite:0.620 alpha:1.000];
                label.font = [UIFont systemFontOfSize:13*VerticalTexeRatio()];
                label.text = property[i][@"mgprName"];
                [_detailScroView addSubview:label];
                
                NSArray * properList = property[i][@"propertyList"];
                NSString * propertyStr = @"";
               
                for (int j = 0; j<properList.count; j++) {
                    propertyStr = [propertyStr stringByAppendingString:properList[j][@"mgprName"]];
                }
                UILabel * infoLabel = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(80, Y+5, 230, 25), YES)];
                infoLabel.textAlignment = NSTextAlignmentLeft;
                infoLabel.textColor = [UIColor colorWithWhite:0.286 alpha:1.000];
                infoLabel.font = [UIFont systemFontOfSize:13*VerticalTexeRatio()];
                infoLabel.numberOfLines = 0;
                infoLabel.text = propertyStr;
                [infoLabel sizeToFit];
                [_detailScroView addSubview:infoLabel];
                
                CGSize size = [infoLabel.text sizeWithFont:[UIFont systemFontOfSize:13*VerticalTexeRatio()]];
                
                Y += size.height +10;
            }
            
            _productDetailImageView.frame = flexibleFrame(CGRectMake(0, Y, 320, 731), YES);
            _detailScroView.contentSize = flexibleSize(CGSizeMake(0, Y+732), YES);
        }
    }else if (tag==SX_SX_PutInShopCar){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
          [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            [self getBagNumber];
        }
    
    
    }else if (tag == SX_AddGoodsCollectInfoTag){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {

            _collectButton.selected = !_collectButton.selected;
        }
    }else if (tag == SX_QueryGoodsUpProperty){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {

            NSArray *arr = database[@"result"];
            if (arr.count < 1) {
                return;
            }
            _perportyDic = database[@"result"][0];
            [_perportyOneArr removeAllObjects];
            _perportyOneArr = database[@"result"][0][@"specifyList"];
            //            for (NSDictionary *dic in database[@"result"][0][@"specifyList"]) {
            //                AppGoodsPerporty *perporty = [[AppGoodsPerporty alloc] initWithDictionary:dic];
            //                [_perportyOneArr addObject:perporty];
            //            }
            _propertyPrice.text = [NSString stringWithFormat:@"￥%.2f",[database[@"result"][0][@"mgsePrice"]floatValue]];
            _propertyNumber.text = [NSString stringWithFormat:@"库存%@件",database[@"result"][0][@"mgspCurrentCount"]];
            //            _typeAndSize.text = database[@"result"][0][@"mgseSpecifyDetailJson"];
            NSMutableArray * titles = [NSMutableArray array];
            NSMutableArray * textsArrays = [NSMutableArray array];
            
            for (int i=0; i<_perportyOneArr.count; i++) {
                NSDictionary *perportyOneDic = _perportyOneArr[i];
                
                _perportyTwoArr = database[@"result"][0][@"specifyList"][i][@"specifyList"];
                [titles addObject:perportyOneDic[@"mgspOoneName"]];
                [textsArrays addObject:database[@"result"][0][@"specifyList"][i][@"specifyList"]];
            }
            AttributScroView * attScroView = [[AttributScroView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 110, 320, 170), YES) titles:titles attributeTextArrays:textsArrays complect:^(NSArray *indexs) {
                NSString * property = @"已选择：";
                NSString * idStr ;
                for (int i = 0; i<indexs.count; i++) {
                    NSArray * array = textsArrays[i];
                    NSString * text = [NSString stringWithFormat:@"“%@”",array[[indexs[i]integerValue]][@"mgspName"]];
                    property = [property stringByAppendingString:text];
                    if (i==0) {
                        idStr = [NSString stringWithFormat:@"%@",array[[indexs[i]integerValue]][@"mgsdId"]];
                    }else{
                        idStr = [idStr stringByAppendingString:[NSString stringWithFormat:@",%@",array[[indexs[i]integerValue]][@"mgsdId"]]];
                    }
                }
                _choseType.text = [property substringFromIndex:4];
                _typeAndSize.text = property;
                _typeAndSize.frame = flexibleFrame(CGRectMake(105, 72, 215, 20), YES);
                [_typeAndSize sizeToFit];
                _typeAndSize.adjustsFontSizeToFitWidth = YES;
                NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
                [dic setObject:@"queryGoodsUpProperty" forKey:@"method"];
                [dic setObject:_goodsId forKey:@"mgooId"];
                [dic setObject:idStr forKey:@"mgseSpecifyDetail"];
                self.shareApi.delegate=self;
                [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGoodsUpProperty withHttpType:@"POST" withTag:SX_QueryGoodsUpPropertyDetail];
                
            }];
            [_propertyView addSubview:attScroView];
            
        }
    }else if (tag == SX_QueryGoodsUpPropertyDetail){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSArray * array = database[@"result"];
            if (array.count == 0) {
                _propertyPrice.text = [NSString stringWithFormat:@"￥%.2f",0.00];
                _propertyNumber.text = [NSString stringWithFormat:@"库存%@件",@"0"];
            }else{
                _mgspId = database[@"result"][0][@"mgspId"];
                _mgspPrice = database[@"result"][0][@"mgsePrice"];
            _propertyPrice.text = [NSString stringWithFormat:@"￥%.2f",[database[@"result"][0][@"mgsePrice"]floatValue]];
            _propertyNumber.text = [NSString stringWithFormat:@"库存%@件",database[@"result"][0][@"mgspCurrentCount"]];
            }
        }
    }else if (tag == SX_QueryCartProductTotalNum){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _productNumLabel.text =[NSString stringWithFormat:@"%@", database[@"result"]];
        }
        
    }else if (tag == SX_SX_queryGoodsIsCollect){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSString * status = database[@"result"];
            if ([status isEqualToString:@"1"]) {
                _collectButton.selected = YES;
            }else{
                _collectButton.selected = NO;
            }
        }
        
    }else if (tag == SX_SX_queryGoodsCommentData){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.commentTableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.commentTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.commitArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.commitArray addObject:entity];
                }
                
                _heightArray = [NSMutableArray array];
                for (int i = 0; i<_commitArray.count; i++) {
                    NSMutableDictionary * dic = _commitArray[i];
                    NSString * image =dic[@"productContentImage"];
                    NSArray * imageArray =  [image componentsSeparatedByString:@","];
                    NSArray * commitArray = @[dic[@"productContent"]];
                   
                    NSInteger height = 0;
                    if (imageArray.count ==0 && commitArray.count == 1) {
                        height = 120;
                    }else if (imageArray.count >0 && commitArray.count == 1){
                        height = 170;
                    }else{
                        for (int j = 0; j<commitArray.count; j++) {
                            NSString * comment = commitArray[j];
                            int lines = 0;
                            CGSize cSize ;
                            if (j==0) {
                                cSize = [comment sizeWithFont:[UIFont systemFontOfSize:14*VerticalTexeRatio()]];
                            }else{
                                cSize = [comment sizeWithFont:[UIFont systemFontOfSize:11*VerticalTexeRatio()]];
                            }
                            
                            if (cSize.width<290*VerticalRatio()) {
                                lines=1;
                            }else{
                                lines = cSize.width/290*VerticalRatio()+1;
                            }
                            height+= lines*(cSize.height);
                        }
                        
                        if (imageArray.count ==0 && commitArray.count >1){
                            height += 120;
                        }else if (imageArray.count >0 && commitArray.count >1){
                            height += 170;
                        }
                    }
                    [_heightArray addObject:@(height)];
                     [dic setObject:imageArray forKey:@"imageArray"];
                     [dic setObject:commitArray forKey:@"commentArray"];
                }
                
                  _commentLabel.text = [NSString stringWithFormat:@"全部评论（%ld）",_commitArray.count];
                _commentTableView.dataSource = self;
                _commentTableView.delegate = self;
                [_commentTableView reloadData];
                
            });
            
            
            
        }

    }else if (tag == SX_QueryMallLoveGoodsDataTag){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else{
            _goodsGuessLikeArray = database[@"result"][@"pageRecord"];
            [self.goodsCollectionView reloadData];
        }
    }else if (tag == SX_SX_queryDesc){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _couponArray = database[@"result"];
         
            _forSaleTableView.dataSource = self;
            _forSaleTableView.delegate = self;
            [_forSaleTableView reloadData];
            
            if (_couponArray.count>0) {
                 _saleLabel.text = [NSString stringWithFormat:@"满%@减%@",_couponArray[0][@"mscoFullAmount"],_couponArray[0][@"mscoDecreaseAmount"]];
            }else{//没有优惠卷
                _productDiscountCouponView.frame = flexibleFrame(CGRectMake(0, CGRectGetMaxY(_forSaleView.frame)/VerticalRatio(), 320, 0), NO);
                _bottomView.frame = flexibleFrame(CGRectMake(0, CGRectGetMinY(_productDiscountCouponView.frame)/VerticalRatio(), 320, 485), NO);
                _mainScroll.contentSize = CGSizeMake(0, CGRectGetMaxY(_bottomView.frame));
            }
            
        }
    }else if (tag == SX_SX_saveUserConpon){
            if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
                
                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                
            }else  {
                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                [UIView animateWithDuration:0.4 animations:^{
                    _forSalePaperView.frame = flexibleFrame(CGRectMake(0, 568, 320, 343), YES);
                } completion:^(BOOL finished) {
                    _maskForSaleButton.hidden=YES;
                    
                }];
            }
    }else if (tag == SX_SX_querySerivceNameByGoodsId){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _goodsServiceName.text = database[@"result"][0][@"mserDesc"];
        }
    }else if (tag == SX_queryGoodsDetailsWebTag){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            //商品详情
            self.productDetailWebUrl= database[@"result"][0][@"mgdeDetailContent"];
            [self.webView loadHTMLString:self.productDetailWebUrl baseURL:nil];
        }
    }else if (tag ==SX_SX_querySpendingSys){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSDictionary * dic = database[@"result"];
            _IntegralBuyLabel.text = [NSString stringWithFormat:@"%@积分可抵%@元现金",dic[@"Spenging"],dic[@"Money"]];
        }
    }
    
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
